package com.ayu.shortlink.project.service.impl;

import com.ayu.shortlink.project.service.UrlTitleService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class UrlTitleServiceImpl implements UrlTitleService {
    @SneakyThrows
    @Override
    public String getLinkTitle(String requestParam) {

        //URL targetUrl= new URL(null, requestParam, new sun.net.www.protocol.https.Handler());
        URL targetUrl = new URL(requestParam);

        HttpURLConnection connection = (HttpURLConnection)targetUrl.openConnection();

        connection.setRequestMethod("GET");
        connection.connect();

        int responseCode = connection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            Document document = Jsoup.connect(requestParam).get();
            return document.title();
        }
        return "Error while fetching title";
    }
}
